package cn.itsource.sender;

import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.message.MessageExt;
import org.junit.Test;

import java.nio.charset.StandardCharsets;
import java.util.List;

public class MessageConsumer {

    @Test
    public void consumer() throws MQClientException {
        //1.创建消费者对象
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("consumer");
        //2.设置nameserver地址
        consumer.setNamesrvAddr("101.35.235.40:9876");
        //3.订阅消息：topic,tags
        consumer.subscribe("topic-order2","tags-order");
        //4.指定消息监听器 : MessageListenerConcurrently:并发消费
        consumer.registerMessageListener(new MessageListenerConcurrently() {
            //消费消息的方法 ： msgs ：消息列表
            @Override
            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs, ConsumeConcurrentlyContext context) {
                for (MessageExt messageExt : msgs) {
                    byte[] body = messageExt.getBody();
                    String bodyStr = new String(body, StandardCharsets.UTF_8);
                    System.out.println("消息的内容："+bodyStr);
                }

                //返回success之后，MQ不再会把该消息投递给消费者
                return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;

                //处理业务逻辑，如果失败了，或者出现异常了，就需要下次重新投递
                //稍后重新投递给我
                //return ConsumeConcurrentlyStatus.RECONSUME_LATER;
            }
        });

        //5.启动消费者
        consumer.start();
        try {
            Thread.sleep(10000000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
}
